// index.js
const app = getApp();
const musicData = require('../../utils/musicData.js');
const storage = require('../../utils/storage.js');
const api = require('../../utils/api.js');

Page({
  data: {
    banners: [],
    radios: [],
    hotSingers: [],
    myPlaylists: [],
    musicList: [],
    currentMusic: null,
    isPlaying: false,
    playProgress: 0,
    loading: false
  },

  onLoad() {
    this.loadData();
    this.initAudioManager();
  },

  onShow() {
    // 更新播放状态
    this.updatePlayStatus();
  },


  // 加载数据（使用真实API）
  loadData() {
    // 显示加载中
    this.setData({ loading: true });
    
    // 轮播图数据（暂时使用本地数据）
    const banners = musicData.getBanners();
    const radios = musicData.getRadios();
    
    // 热门歌手数据
    const hotSingers = [
      { id: 1, name: '周杰伦', avatar: 'https://bkimg.cdn.bcebos.com/pic/2fdda3cc7cd98d1001e913331664af0e7bec54e73a24?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_1000', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', songs: 328 },
      { id: 2, name: '林俊杰', avatar: 'https://bkimg.cdn.bcebos.com/pic/86d6277f9e2f0708283872b67b7caf99a9014c085476?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_1000', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', songs: 256 },
      { id: 3, name: '陈奕迅', avatar: 'https://bkimg.cdn.bcebos.com/pic/ac345982b2b7d0a20cf4c52da8b661094b36acaf2c73?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_500', color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)', songs: 412 },
      { id: 4, name: '邓紫棋', avatar: 'https://bkimg.cdn.bcebos.com/pic/77094b36acaf2edda3cc09ac644616e93901213f3565?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_1000', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', songs: 189 },
      { id: 5, name: '薛之谦', avatar: 'https://bkimg.cdn.bcebos.com/pic/fd039245d688d43fa2280692751ed21b0ff43bc8?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_650', color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', songs: 234 },
      { id: 6, name: '张学友', avatar: 'https://bkimg.cdn.bcebos.com/pic/a2cc7cd98d1001e93901b48a75576cec54e737d139a6?x-bce-process=image/format,f_auto/resize,m_lfit,limit_1,h_500', color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)', songs: 523 }
    ];
    
    // 我的歌单数据
    const myPlaylists = [
      { id: 1, name: '我喜欢的音乐', cover: 'https://picsum.photos/seed/playlist1/400/400', count: 52 },
      { id: 2, name: '华语经典', cover: 'https://picsum.photos/seed/playlist2/400/400', count: 38 },
      { id: 3, name: '欧美流行', cover: 'https://picsum.photos/seed/playlist3/400/400', count: 45 },
      { id: 4, name: '抖音神曲', cover: 'https://picsum.photos/seed/playlist4/400/400', count: 67 },
      { id: 5, name: '安静纯音乐', cover: 'https://picsum.photos/seed/playlist5/400/400', count: 29 }
    ];
    
    this.setData({
      banners,
      radios,
      hotSingers,
      myPlaylists
    });

    // 从后端API加载歌曲列表
    api.getSongPage(1, 20).then(res => {
      console.log('获取歌曲列表成功：', res);
      
      // 处理数据格式，适配小程序
      const musicList = res.records.map(song => {
        // 处理音乐URL
        let musicUrl = song.url;
        // 如果是相对路径，添加BASE_URL
        if (musicUrl && !musicUrl.startsWith('http')) {
          musicUrl = api.BASE_URL + musicUrl;
        }
        
        // 处理封面图片URL
        let coverUrl = song.pic;
        if (coverUrl && !coverUrl.startsWith('http')) {
          coverUrl = api.BASE_URL + coverUrl;
        } else if (!coverUrl) {
          coverUrl = '/images/default-cover.jpg';
        }
        
        console.log(`歌曲: ${song.name}, URL: ${musicUrl}`);
        
        return {
          id: song.id,
          title: song.name,
          singer: song.singerName || '未知歌手',
          coverImgUrl: coverUrl,
          src: musicUrl, // 使用src字段，与播放器一致
          lyric: song.lyric || ''
        };
      });
      
      this.setData({
        musicList,
        loading: false
      });
      
      console.log('处理后的歌曲列表：', musicList);
    }).catch(err => {
      console.error('获取歌曲列表失败：', err);
      // 失败时使用本地数据
      const musicList = musicData.getAllMusic();
      this.setData({
        musicList,
        loading: false
      });
      wx.showToast({
        title: '加载失败，使用本地数据',
        icon: 'none'
      });
    });
  },

  // 初始化音频管理器
  initAudioManager() {
    const audioManager = app.globalData.audioManager;
    
    // 监听播放
    audioManager.onPlay(() => {
      this.setData({ isPlaying: true });
    });
    
    // 监听暂停
    audioManager.onPause(() => {
      this.setData({ isPlaying: false });
    });
    
    // 监听停止
    audioManager.onStop(() => {
      this.setData({ isPlaying: false });
    });
    
    // 监听播放进度
    audioManager.onTimeUpdate(() => {
      if (audioManager.duration > 0) {
        const progress = (audioManager.currentTime / audioManager.duration) * 100;
        this.setData({ playProgress: progress });
      }
    });
    
    // 监听播放结束
    audioManager.onEnded(() => {
      this.playNext();
    });
    
    // 监听错误
    audioManager.onError((err) => {
      console.error('音频播放错误', err);
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      });
    });
  },

  // 更新播放状态
  updatePlayStatus() {
    const audioManager = app.globalData.audioManager;
    const currentMusic = app.globalData.currentMusic;
    
    if (currentMusic) {
      this.setData({
        currentMusic,
        isPlaying: !audioManager.paused
      });
    }
  },

  // 播放音乐
  playMusic(e) {
    const index = e.currentTarget.dataset.index;
    const music = this.data.musicList[index];
    
    console.log('🎵 点击播放，索引：', index);
    console.log('🎵 歌曲信息：', music);
    
    if (!music) {
      console.error('❌ 找不到歌曲！');
      return;
    }
    
    if (!music.src) {
      console.error('❌ 歌曲没有src字段！', music);
      wx.showToast({
        title: '歌曲地址错误',
        icon: 'none'
      });
      return;
    }
    
    console.log('🎵 歌曲URL：', music.src);
    
    // 保存到全局数据
    app.globalData.currentMusic = music;
    app.globalData.playlist = this.data.musicList;
    app.globalData.playIndex = index;
    
    // 添加到播放历史
    storage.addPlayHistory(music);
    
    // 播放音乐
    this.startPlay(music);
    
    this.setData({
      currentMusic: music,
      isPlaying: true
    });
  },

  // 开始播放
  startPlay(music) {
    const audioManager = app.globalData.audioManager;
    
    console.log('🎼 开始播放：', music.title);
    console.log('🎼 音频URL：', music.src);
    
    try {
      audioManager.title = music.title;
      audioManager.singer = music.singer;
      audioManager.coverImgUrl = music.coverImgUrl;
      audioManager.src = music.src;
      
      console.log('✅ 音频管理器已设置');
      
      wx.showToast({
        title: '正在播放：' + music.title,
        icon: 'none',
        duration: 2000
      });
    } catch (err) {
      console.error('❌ 播放失败：', err);
      wx.showToast({
        title: '播放失败：' + err.message,
        icon: 'none'
      });
    }
  },

  // 播放/暂停底部播放器
  togglePlay() {
    const audioManager = app.globalData.audioManager;
    
    if (!this.data.currentMusic) {
      // 如果没有当前音乐，播放第一首
      if (this.data.musicList.length > 0) {
        this.playMusic({ currentTarget: { dataset: { index: 0 } } });
      }
      return;
    }
    
    if (this.data.isPlaying) {
      audioManager.pause();
    } else {
      audioManager.play();
    }
  },

  // 播放下一首
  playNext() {
    const playlist = app.globalData.playlist;
    const currentIndex = app.globalData.playIndex;
    
    if (!playlist || playlist.length === 0) return;
    
    const nextIndex = (currentIndex + 1) % playlist.length;
    const nextMusic = playlist[nextIndex];
    
    app.globalData.currentMusic = nextMusic;
    app.globalData.playIndex = nextIndex;
    
    storage.addPlayHistory(nextMusic);
    this.startPlay(nextMusic);
    
    this.setData({
      currentMusic: nextMusic,
      isPlaying: true
    });
  },

  // 跳转到播放器页面
  goToPlayer() {
    if (this.data.currentMusic) {
      wx.navigateTo({
        url: '/pages/player/player'
      });
    }
  },

  // 点击轮播图
  onBannerTap(e) {
    const index = e.currentTarget.dataset.index;
    console.log('点击轮播图', index);
    // 可以根据轮播图类型跳转到不同页面
  },

  // 点击电台
  onRadioTap(e) {
    const id = e.currentTarget.dataset.id;
    console.log('点击电台', id);
    // 可以跳转到电台详情页面
  }
});
